package com.jinlejia.feedback.question.ui;

import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.jinlejia.common.weight.JLJProgressDialog;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.feedback.R;
import com.jinlejia.feedback.common.FbApiConfig;
import com.jinlejia.feedback.common.databinding.CommonEvent;
import com.jinlejia.feedback.databinding.FbActivityRespondToDetailsBinding;
import com.jinlejia.feedback.idea.ui.adapter.RespondToDetailsAdapter;
import com.jinlejia.feedback.idea.ui.bean.RespondToDetailsBean;
import com.jinlejia.feedback.question.http.QuestionDetailsHelper;
import com.utils.SoftKeyBoardEvent;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * @author SongJiaTai
 * @description:回复详情Activity
 * @date :2019/7/2 21:26
 */
public class FbRespondToDetailsActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
    private FbActivityRespondToDetailsBinding binding;
    private String replyCode;
    private ArrayList<RespondToDetailsBean> mList = new ArrayList<>();
    private RespondToDetailsAdapter adapter;
    private QuestionDetailsHelper helper;


    private String replyUserPortrait;//回复人头像String
    private String replyCode1;//回复编码String
    private String replyUserName;//回复人姓名String
    private String replyUserDept;//回复人部门String
    private String replyUserDuty;//回复人职务
    private String replyContent;//回复内容
    private String replyTime;//回复时间
    private Integer replylikeCount;//点赞数
    private Integer replylikeState;//点赞状态
    private String replyUserId;//回复人ID
    private JSONObject jsonObject = new JSONObject();

    private String problemCode;//问题编码


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.fb_activity_respond_to_details);
        binding.setCommonEvent(CommonEvent.obtain());
        binding.setEvent(this);
        Intent intent = getIntent();
        replyCode = intent.getStringExtra("replyCode");
        problemCode = intent.getStringExtra("problemCode");
        adapter = new RespondToDetailsAdapter(mList);
        binding.yfListRecyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        binding.yfListRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.yfListRecyclerView.setHasFixedSize(true);
        binding.yfListRecyclerView.setAdapter(adapter);
        binding.swipeRefreshLayout.setOnRefreshListener(this);
        adapter.changeMode(YfListMode.MODE_LOADING);
        helper = new QuestionDetailsHelper();
        initData(replyCode);
        initview();

    }


    //region 加载框dialog
    private JLJProgressDialog progressDialog;

    private void showProgressDialog(String tip) {
        closeProgressDialog();
        progressDialog = new JLJProgressDialog(this, tip, false);
        progressDialog.show();
    }

    private void closeProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        progressDialog = null;
    }
    //endregion

    private void initview() {
        adapter.setLiketEvent(new RespondToDetailsAdapter.LiketEvent() {
            @Override
            public void onLikeListener(boolean islike, String likeCode, QuestionDetailsHelper.LikeType likeType, final RespondToDetailsBean respondToDetailsBean, final int position) {
                helper.likeOperation(islike, likeCode, likeType, new QuestionDetailsHelper.LikeOrCollectCallBack() {
                    @Override
                    public void onSuccess(QuestionDetailsHelper.LikeOrCollectType likeOrCollect, QuestionDetailsHelper.LikeType likeType, boolean state, int count) {
                        int oldState = respondToDetailsBean.getLikeState();
                        int oldCount = respondToDetailsBean.getLikeCount();
                        int temState;
                        if (!state) {
                            temState = 0;
                        } else {
                            temState = 1;
                        }
                        if (oldState == temState && oldCount == count) { //如果数据没有变化则，不进行重新绘画ITEM修改
                            respondToDetailsBean.setLikeCount(count);
                            respondToDetailsBean.setLikeState(temState);
                        } else {
                            respondToDetailsBean.setLikeCount(count);
                            respondToDetailsBean.setLikeState(temState);
                            adapter.notifyItemChanged(position);
                        }
                    }

                    @Override
                    public void onFailed(String message) {
                        CustomToast.showToast(FbRespondToDetailsActivity.this, message, 1500);
                    }
                });
            }
        });


        adapter.setReplyInfoEvent(new RespondToDetailsAdapter.replyInfoEvent() {
            @Override
            public void onReplyInfoListener(String replyCode, String commentTargetUserId, String commentTargetUserName) {
                binding.inputEditText.setFocusable(true);
                binding.inputEditText.setFocusableInTouchMode(true);
                binding.inputEditText.requestFocus();
                binding.inputEditText.findFocus();
                binding.inputEditText.setHint("回复："+commentTargetUserName);
                InputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(getApplicationContext().INPUT_METHOD_SERVICE);
                imm.showSoftInput(binding.inputEditText, InputMethodManager.SHOW_FORCED);// 显示输入法

                replyCode1 = replyCode;
                replyUserId = commentTargetUserId;
                replyUserName = commentTargetUserName;

            }
        });


//region 是否输入改变按钮样式监听
        binding.inputEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().isEmpty()) {
                    binding.submitAnnounceInfoButton.setEnabled(false);
                } else {
                    binding.submitAnnounceInfoButton.setEnabled(true);
                }
            }
        });
//endregion


//region 键盘监听
        SoftKeyBoardEvent.setListener(this, new SoftKeyBoardEvent.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                binding.submitAnnounceInfoButton.setVisibility(View.VISIBLE);
            }

            @Override
            public void keyBoardHide(int height) {

                binding.submitAnnounceInfoButton.setVisibility(View.GONE);
            }
        });
        //endregion


        binding.replyInfoTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initDataList(replyCode);
                binding.inputEditText.setFocusable(true);
                binding.inputEditText.setFocusableInTouchMode(true);
                binding.inputEditText.setHint("回复："+replyUserName);
                binding.inputEditText.requestFocus();
                binding.inputEditText.findFocus();
                InputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(getApplicationContext().INPUT_METHOD_SERVICE);
                imm.showSoftInput(binding.inputEditText, InputMethodManager.SHOW_FORCED);// 显示输入法
            }
        });
    }


    //region 刷新列表方法
    private void initDataList(String code) {
        OkHttpUtils.get()
                .url(FbApiConfig.Respondtodetails)
                .addParams("replyCode", code)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        CustomToast.showToast(FbRespondToDetailsActivity.this, "网络连接失败", 1500);
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (showEmptyMessage(response)) return;
                        JSONObject data = JSON.parseObject(response.get("data").toString());
                        JSONArray list = data.getJSONArray("replyCommentList");
                        mList = (ArrayList<RespondToDetailsBean>) JSON.parseArray(list.toString(), RespondToDetailsBean.class);
                        adapter.setData(mList);
                        adapter.notifyDataSetChanged();

                        replyCode1 = data.getString("replyCode");//回复编码String
                        replyUserPortrait = data.getString("replyUserPortrait");//回复人头像String
                        replyUserName = data.getString("replyUserName");//回复人姓名String
                        replyUserDept = data.getString("replyUserDept");//回复人部门String
                        replyUserDuty = data.getString("replyUserDuty");//回复人职务String
                        replyContent = data.getString("replyContent");//回复内容String
                        replyTime = data.getString("replyTime");//回复时间String
                        replylikeCount = data.getInteger("likeCount");//点赞数int
                        replylikeState = data.getInteger("likeState");//点赞状态int
                        replyUserId = data.getString("replyUserId");//回复人IDsString
                    }
                });
    }
//endregion

    //region 初始化所有数据请求
    private void initData(String replyCode) {
        OkHttpUtils.get()
                .url(FbApiConfig.Respondtodetails)
                .addParams("replyCode", replyCode)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        binding.swipeRefreshLayout.setRefreshing(false);
                        CustomToast.showToast(FbRespondToDetailsActivity.this, "网络连接失败", 1500);
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (showEmptyMessage(response)) return;
                        JSONObject data = JSON.parseObject(response.get("data").toString());
                        JSONArray list = data.getJSONArray("replyCommentList");
                        mList = (ArrayList<RespondToDetailsBean>) JSON.parseArray(list.toString(), RespondToDetailsBean.class);
                        adapter.setData(mList);
                        adapter.notifyDataSetChanged();


                        replyCode1 = data.getString("replyCode");//回复编码String
                        replyUserPortrait = data.getString("replyUserPortrait");//回复人头像String
                        replyUserName = data.getString("replyUserName");//回复人姓名String
                        replyUserDept = data.getString("replyUserDept");//回复人部门String
                        replyUserDuty = data.getString("replyUserDuty");//回复人职务String
                        replyContent = data.getString("replyContent");//回复内容String
                        replyTime = data.getString("replyTime");//回复时间String
                        replylikeCount = data.getInteger("likeCount");//点赞数int
                        replylikeState = data.getInteger("likeState");//点赞状态int
                        replyUserId = data.getString("replyUserId");//回复人IDsString
                        binding.swipeRefreshLayout.setRefreshing(false);

                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        binding.tvTitle.setText(replyUserName+"的回复");
                                        binding.likeStateImageView.setVisibility(View.VISIBLE);
                                        binding.userNameTextView.setText(replyUserName);
                                        //用户部门 or  职务
                                        String userInfo = replyUserDuty; //用户职务
                                        if (!TextUtils.isEmpty(replyUserDept)) {
                                            //如果部门为null 则显示职务
                                            userInfo = replyUserDept;
                                        }
                                        binding.userInfoTextView.setText(userInfo);
                                        binding.replyTimeTextView.setText(replyTime);
                                        binding.replyInfoTextView.setText(replyContent);
                                        Glide.with(binding.userIconImageView.getContext())
                                                .load(replyUserPortrait)
                                                .placeholder(R.mipmap.jlj_role_head)
                                                .error(R.mipmap.jlj_role_head)
                                                .into(binding.userIconImageView);


                                        int likeCount;
                                        final boolean isLike;
                                        try {
                                            likeCount = replylikeCount;//点赞数量
                                        } catch (Exception e) {
                                            likeCount = 0;
                                        }
                                        int likeState = replylikeState;
                                        if (likeState == 0) {
                                            isLike = false;
                                        } else {
                                            isLike = true;
                                        }

                                        binding.likeCountTextView.setText(String.valueOf(likeCount));
                                        if (isLike) {
                                            binding.likeStateImageView.setImageResource(R.mipmap.fb_like_icon);
                                            binding.likeCountTextView.setTextColor(Color.parseColor("#FCCB00"));
                                        } else {
                                            binding.likeStateImageView.setImageResource(R.mipmap.fb_unlike_icon);
                                            binding.likeCountTextView.setTextColor(Color.parseColor("#999999"));
                                        }

                                        binding.likeOperateLayout.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                int count = Integer.parseInt(binding.likeCountTextView.getText().toString());
                                                int likeState = replylikeState;
                                                boolean isLike;
                                                if (likeState == 1) {
                                                    isLike = true;
                                                } else {
                                                    isLike = false;
                                                }
                                                if (isLike) {
                                                    binding.likeStateImageView.setImageResource(R.mipmap.fb_unlike_icon);
                                                    binding.likeCountTextView.setTextColor(Color.parseColor("#999999"));
                                                    count = count - 1;
                                                } else {
                                                    binding.likeStateImageView.setImageResource(R.mipmap.fb_like_icon);
                                                    binding.likeCountTextView.setTextColor(Color.parseColor("#FCCB00"));
                                                    count = count + 1;

                                                }
                                                binding.likeCountTextView.setText(String.valueOf(count));
                                                helper.likeOperation(isLike, replyCode1, QuestionDetailsHelper.LikeType.Reply, new QuestionDetailsHelper.LikeOrCollectCallBack() {
                                                    @Override
                                                    public void onSuccess(QuestionDetailsHelper.LikeOrCollectType likeOrCollect, QuestionDetailsHelper.LikeType likeType, boolean state, int count) {

                                                    }

                                                    @Override
                                                    public void onFailed(String message) {
                                                        CustomToast.showToast(FbRespondToDetailsActivity.this, message, 1500);
                                                    }
                                                });
                                                int likestatew;
                                                if (isLike) {
                                                    likestatew = 0;
                                                } else {
                                                    likestatew = 1;
                                                }
                                                replylikeState = likestatew;
                                                replylikeCount = count;
                                            }
                                        });

                                    }
                                });
                            }
                        }).start();
                    }
                });

    }
    //endregion

    private boolean showEmptyMessage(Map<String, Object> response) {
        if ("501".equals(String.valueOf(response.get("code")))) {
            if (response.get("message") != null)
                CustomToast.showToast(FbRespondToDetailsActivity.this, response.get("message").toString(), 1500);
            return true;
        }
        return false;
    }


    //region 发表按钮点击事件
    public void putonclick(View view) {
        showProgressDialog(null);
        String text = binding.inputEditText.getText().toString();
        helper.saveReplyComment(problemCode, replyCode1, replyUserId, replyUserName, text, new QuestionDetailsHelper.SaveReplyCommentCallBack() {
            @Override
            public void onResult(boolean flag, String message) {
                if (flag){
                    closeProgressDialog();
                    initDataList(replyCode);
                    CustomToast.showToast(FbRespondToDetailsActivity.this,"发表成功",1500);
                    binding.inputEditText.setText(null);
                    InputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);//隐藏输入法
                }else{
                    closeProgressDialog();
                    CustomToast.showToast(FbRespondToDetailsActivity.this,message,1500);
                }


            }
        });
    }

    @Override
    public void onRefresh() {
        initData(replyCode);
    }

    //endregion
}
